package com.tan.lbs.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.tan.lbs.dao.NPCDAO;
import com.tan.lbs.entity.NPC;
import com.tan.lbs.util.HibernateUtil;

public class NPCDAOImpl implements NPCDAO {

	@Override
	public String create(NPC npc) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		s.save(npc);
		s.getTransaction().commit();
		return npc.getNpcID();
	}

	@Override
	public NPC readByID(String npcID) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		NPC npc = (NPC)s.get(NPC.class, npcID);
		s.getTransaction().commit();
		return npc;
	}

	@Override
	public void update(NPC npc) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		s.update(npc);
		s.getTransaction().commit();

	}

	@Override
	public ArrayList<NPC> searchByGame(String gameID) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		List<NPC> gs = s.createCriteria(NPC.class).add(Restrictions.
				eq("gameID", gameID)).list();
		s.getTransaction().commit();
		return new ArrayList<NPC>(gs);
	}

	@Override
	public void delete(String npcID) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session s = sf.getCurrentSession();
		s.beginTransaction();
		NPC npc = new NPC();
		npc.setNpcID(npcID);
		s.delete(npc);
		s.getTransaction().commit();	
	}

}
